<script setup>
import { ref } from 'vue'
import { useAuthStore } from '@/stores/modules/auth'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message} from '@element-plus/icons-vue'

const registerForm = ref({
  username: '',
  password: '',
  email: ''
})
const formRef = ref()
const authStore = useAuthStore()
const router = useRouter()
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 15, message: '用户名必须是5-15位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ]
}
// 修改register方法，添加详细错误打印
const register = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 构建提交数据
        const submitData = {
          username: registerForm.value.username,
          password: registerForm.value.password
        }
        // 只有当邮箱不为空时才添加email字段
        if (registerForm.value.email && registerForm.value.email.trim()) {
          submitData.email = registerForm.value.email.trim()
        }
        const response = await authStore.handleRegister(submitData)
        console.log('注册成功:', response)
        ElMessage.success('注册成功！')
        router.push('/login')
      } catch (error) {
        // 显示后端返回的具体错误
        const errorMsg = error.response?.data?.error || '注册失败，请重试'
        ElMessage.error(errorMsg)
      }
    } else {
      console.log('表单验证失败:', fields)
      ElMessage.error('请填写正确的表单信息')
    }
  })
}

</script>

<template>
  <div class="register-page">
    <el-card class="register-card">
      <template #header>
        <h2>用户注册</h2>
      </template>

      <el-form  :model="registerForm" ref="formRef" :rules="rules" @submit.prevent="register" label-position="top">
        <el-form-item label="用户名" required prop="username">
          <el-input :prefix-icon="User" v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" required prop="password">
          <el-input
            :prefix-icon="Lock"
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            :prefix-icon="Message"
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱（可选）"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="success" @click="register" style="width: 100%">
            注册
          </el-button>
        </el-form-item>
      </el-form>

      <div class="link-text">
        已有账号？ <el-link type="success" @click="router.push('/login')">立即登录</el-link>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.register-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.register-card {
  width: 400px;
  max-width: 90%;
}

.register-card h2 {
  text-align: center;
  margin: 0;
  color: #303133;
}

.link-text {
  text-align: center;
  margin-top: 20px;
  color: #606266;
}
</style>
